<template>
  <px-dialog v-model="visible" class="equip-dialog-wrap" :title="typeTitle" width="800px" @open="openDialog" @close="closeDialog">
    <px-form ref="formRef" :model="formValue" :rules="rules" label-position="right" label-width="120px">
      <px-form-item label="事件类型" prop="eventType">
        <px-select v-model="formValue.eventType" filterable clearable placeholder="请选择事件类型" @change="formValue.isScreen = 0">
          <px-option v-for="item in eventTypeList" :key="item.value" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="文档名称" prop="documentName">
        <px-input v-model="formValue.documentName" placeholder="请输入文档名称" maxlength="50" clearable show-word-limit />
      </px-form-item>
      <px-form-item
        v-if="formValue.eventType === 'gas_alarm' || formValue.eventType === 'fire_alarm' || formValue.eventType === ''"
        label="是否默认投屏"
        prop="isScreen"
      >
        <px-radio-group v-model="formValue.isScreen">
          <px-radio :label="1">是</px-radio>
          <px-radio :label="0">否</px-radio>
        </px-radio-group>
      </px-form-item>
      <px-form-item label="文档文件" prop="fileId" :rules="[{ required: true, validator: validateAttach, trigger: 'change' }]">
        <FileUpload
          :countLimit="1"
          fileType="add"
          fileAccept="pdf"
          fileTypeValue="pdf"
          fileTitle="文件"
          :fileData="{ moduleName: 'erc_learn' }"
          :fileLists="fileList"
          :fileSize="100"
          @changeFileList="changeFileList"
          @saveFileStatus="saveFileStatus"
        />
      </px-form-item>
    </px-form>
    <div class="equip-dialog-footer">
      <px-button @click="closeDialog">取消</px-button>
      <px-button :disabled="fileStatusFlag" type="primary" @click="handleSubmit(formRef)">保存</px-button>
    </div>
  </px-dialog>
</template>
<script setup lang="ts">
import { addAlarmDocument, editAlarmDocument } from "@/api/erc/learn";
import { PxMessage } from "px-ui";
import { computed, reactive, ref, toRefs } from "vue";
import FileUpload from "./FileUpload.vue";

// 调用父级-关闭弹窗、查询列表方法
const emits = defineEmits(["closeDialog", "queryTable"]);
// 父级传过来的值
const props = defineProps(["dialogVisible", "dialogType", "dialogRow", "eventTypeList"]);
const visible = computed(() => props.dialogVisible);

// 页面本身的值
const formRef = ref();
const state = reactive<any>({
  typeTitle: "新增报警文档",
  formValue: {
    id: "",
    eventType: "",
    documentName: "",
    isScreen: 0,
    fileId: 0
  },
  fileList: [],
  fileStatusFlag: false
});
const { formValue, typeTitle, fileList, fileStatusFlag } = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  eventType: [{ required: true, message: "事件类型不能为空", trigger: "change" }],
  documentName: [{ required: true, message: "文档名称不能为空", trigger: "blur" }],
  isScreen: [{ required: true, message: "是否默认投屏不能为空", trigger: "change" }]
}));
// 校验文档文件
const validateAttach = (rule, value, callback) => {
  if (fileList.value.length <= 0) {
    callback(new Error("文档文件不能为空"));
  }
  callback();
};

// 打开弹窗
const openDialog = async () => {
  formRef.value?.resetFields();
  if (props.dialogType === "add") {
    typeTitle.value = "新增报警文档";
    formValue.value.eventType = "";
    formValue.value.documentName = "";
    formValue.value.isScreen = 0;
    formValue.value.fileId = 0;
    fileList.value = [];
    delete formValue.value.id;
  } else if (props.dialogType === "edit") {
    typeTitle.value = "编辑报警文档";
    const { id, eventType, documentName, isScreen, fileId, fileDTO } = JSON.parse(JSON.stringify(props.dialogRow));
    formValue.value.id = id;
    formValue.value.eventType = eventType;
    formValue.value.documentName = documentName;
    formValue.value.isScreen = isScreen;
    formValue.value.fileId = fileId;
    fileList.value = [];
    fileList.value = [fileDTO];
  }
};
// 关闭弹窗
const closeDialog = () => {
  formRef.value?.resetFields();
  emits("closeDialog");
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      formValue.value.fileId = 0;
      if (fileList.value && fileList.value.length > 0) {
        if (fileList.value[0]?.id) {
          formValue.value.fileId = fileList.value[0].id;
        } else if (fileList.value[0]?.response.data.id) {
          formValue.value.fileId = fileList.value[0].response.data.id;
        }
      }
      const params = JSON.parse(JSON.stringify(formValue.value));
      if (formValue.value.eventType === "gas_alarm" || formValue.value.eventType === "fire_alarm") {
      } else {
        delete params.isScreen;
      }
      if (props.dialogType === "add") {
        await addAlarmDocument(params);
        PxMessage.success("新增成功");
        emits("closeDialog");
        emits("queryTable");
      } else if (props.dialogType === "edit") {
        await editAlarmDocument(params);
        PxMessage.success("编辑成功");
        emits("closeDialog");
        emits("queryTable");
      }
    }
  });
};

// 新的报警文档列表
const changeFileList = val => {
  fileList.value = val;
  if (val.length > 0) {
    // 1、文档列表不为空，清空校验
    formRef.value.clearValidate("fileId");
  } else {
    // 2、因为删除等操作文档列表为空，重新校验
    formRef.value.validateField("fileId");
  }
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
</script>
<style lang="scss" scoped>
@import url("@/views/erc/scss/add-dialog.scss");

.equip-dialog-wrap {
  .equip-dialog-footer {
    margin-top: 20px;
    text-align: right;
  }
}

:deep(.px-tree) {
  .px-tree-node {
    .px-tree-node__content {
      .px-checkbox {
        .px-checkbox__input {
          .px-checkbox__inner {
            display: none;
          }
        }
      }

      .is-leaf + .px-checkbox {
        .px-checkbox__inner {
          display: inline-block;
        }
      }
    }
  }
}
</style>
